<template>
  <div class="window-management-container">
    <div class="page-header">
      <h2 class="page-title">窗口管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateWindow">
          <el-icon><Plus /></el-icon>新建窗口
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索过滤器 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="窗口编号">
          <el-input v-model="filterForm.number" placeholder="请输入窗口编号" clearable />
        </el-form-item>
        <el-form-item label="窗口名称">
          <el-input v-model="filterForm.name" placeholder="请输入窗口名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="开放" :value="'OPEN'" />
            <el-option label="暂停" :value="'PAUSE'" />
            <el-option label="关闭" :value="'CLOSED'" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 窗口表格 -->
    <div class="window-table">
      <el-table
        :data="displayWindowList"
        style="width: 100%"
        v-loading="tableLoading"
        border
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="id" label="窗口编号" width="100" />
        <el-table-column prop="name" label="窗口名称" min-width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 'OPEN' ? '开放' : scope.row.status === 'PAUSE' ? '暂停' : '关闭'}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button size="small" @click="handleEditWindow(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDeleteWindow(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新建/编辑窗口对话框 -->
    <el-dialog
      v-model="windowDialog.visible"
      :title="windowDialog.isEdit ? '编辑窗口' : '新建窗口'"
      width="600px"
    >
      <el-form
        ref="windowFormRef"
        :model="windowForm"
        :rules="windowRules"
        label-width="120px"
      >
        <el-form-item label="窗口编号" prop="id">
          <el-input type="number" v-model="windowForm.id" placeholder="请输入窗口编号" />
        </el-form-item>
        <el-form-item label="窗口名称" prop="name">
          <el-input v-model="windowForm.name" placeholder="请输入窗口名称" />
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input
            v-model="windowForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="windowForm.status" placeholder="请选择状态" clearable>
            <el-option label="开放" :value="'OPEN'" />
            <el-option label="暂停" :value="'PAUSE'" />
            <el-option label="关闭" :value="'CLOSED'" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="windowDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitWindowForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 配置业务类型对话框 -->
    <el-dialog
      v-model="businessTypeDialog.visible"
      title="配置业务类型"
      width="600px"
    >
      <div v-if="businessTypeDialog.windowName" class="business-type-title">
        为 <strong>{{ businessTypeDialog.windowName }}</strong> 配置业务类型
      </div>
      <el-transfer
        v-model="businessTypeDialog.selectedTypes"
        :data="businessTypeOptions"
        :titles="['可选业务类型', '已选业务类型']"
        :button-texts="['移除', '添加']"
        @change="handleBusinessTypeChange"
      />

      <template #footer>
        <el-button @click="businessTypeDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveBusinessTypes">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'
import axios from "axios";

export default {
  name: 'WindowManagement',
  components: {
    Plus,
    Refresh,
    Search
  },
  setup() {
    // 模拟业务类型数据
    const mockBusinessTypes = [
      { id: 1, name: '普通业务', code: 'A' },
      { id: 2, name: '特殊业务', code: 'B' },
      { id: 3, name: '紧急业务', code: 'C' },
      { id: 4, name: '企业业务', code: 'D' },
      { id: 5, name: '临时业务', code: 'E' }
    ]

    // 窗口列表数据
    const windowList = ref([])
    const tableLoading = ref(false)

    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })

    // 过滤表单
    const filterForm = reactive({
      number: '',
      name: '',
      status: ''
    })

    function getList() {
      let params = {
        pageNum: pagination.currentPage,
        pageSize: pagination.pageSize,
      };
      if (checkStrNotEmpty(filterForm.name)) {
        params.name = filterForm.name
      }
      if (checkStrNotEmpty(filterForm.status)) {
        params.status = filterForm.status
      }
      windowList.value = [];
      tableLoading.value = true;
      axios.get("/windows/getList", {
        params: params
      }).then(res => {
        res.data.data.list.forEach(item => {
          windowList.value.push(item);
          tableLoading.value = false;
        })
        pagination.total = res.data.data.total;
      });
    }

    function checkStrNotEmpty(str) {
      return str !== undefined && str !== null && str !== '' && str.trim() !== '';
    }

    getList();

    // 窗口对话框
    const windowDialog = reactive({
      visible: false,
      isEdit: false
    })

    // 窗口表单
    const windowFormRef = ref(null)
    const windowForm = reactive({
      id: null,
      name: '',
      location: '',
      deviceId: '',
      description: '',
      status: "OPEN"
    })

    // 业务类型配置对话框
    const businessTypeDialog = reactive({
      visible: false,
      windowId: null,
      windowName: '',
      selectedTypes: []
    })

    // 业务类型选项
    const businessTypeOptions = mockBusinessTypes.map(item => ({
      key: item.id,
      label: `${item.name} (${item.code})`,
      disabled: false
    }))

    // 表单验证规则
    const windowRules = {
      id: [
        { required: true, message: '请输入窗口编号', trigger: 'blur' },
      ],
      name: [
        { required: true, message: '请输入窗口名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      location: [
        { required: true, message: '请输入窗口位置', trigger: 'blur' }
      ],
      deviceId: [
        { required: true, message: '请输入设备ID', trigger: 'blur' }
      ]
    }

    // 根据筛选条件和分页显示窗口列表
    const displayWindowList = computed(() => {
      // 应用筛选条件
      let filteredList = windowList.value.filter(item => {
        let numberMatch = true, nameMatch = true, statusMatch = true

        if (filterForm.number) {
          numberMatch = item.number.includes(filterForm.number)
        }

        if (filterForm.name) {
          nameMatch = item.name.includes(filterForm.name)
        }

        if (filterForm.status !== '') {
          statusMatch = item.status === filterForm.status
        }

        return numberMatch && nameMatch && statusMatch
      })

      // 应用分页
      const start = (pagination.currentPage - 1) * pagination.pageSize
      const end = start + pagination.pageSize

      return filteredList.slice(start, end)
    })

    // 监听筛选列表变化更新总数
    const updatePaginationTotal = () => {
      const filteredList = windowList.value.filter(item => {
        let numberMatch = true, nameMatch = true, statusMatch = true

        if (filterForm.number) {
          numberMatch = item.number.includes(filterForm.number)
        }

        if (filterForm.name) {
          nameMatch = item.name.includes(filterForm.name)
        }

        if (filterForm.status !== '') {
          statusMatch = item.status === filterForm.status
        }

        return numberMatch && nameMatch && statusMatch
      })

      pagination.total = filteredList.length
    }

    // 监听过滤条件变化
    watch([() => filterForm.number, () => filterForm.name, () => filterForm.status], () => {
      updatePaginationTotal()
    })

    // 监听窗口列表变化
    watch(windowList, () => {
      updatePaginationTotal()
    }, { deep: true })

    // 处理搜索
    const handleSearch = () => {
      pagination.currentPage = 1
    }

    // 重置过滤器
    const resetFilter = () => {
      Object.keys(filterForm).forEach(key => {
        filterForm[key] = ''
      })
      pagination.currentPage = 1
    }

    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
    }

    // 处理页码变化
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
    }

    // 处理刷新
    const handleRefresh = () => {
      tableLoading.value = true
      setTimeout(() => {
        tableLoading.value = false
        ElMessage.success('刷新成功')
      }, 500)
    }

    // 处理新建窗口
    const
        handleCreateWindow = () => {
      windowDialog.isEdit = false
      windowDialog.visible = true

      Object.keys(windowForm).forEach(key => {
        if (key === 'status') {
          windowForm[key] = 1
        } else {
          windowForm[key] = ''
        }
      })
    }

    // 处理编辑窗口
    const handleEditWindow = (row) => {
      windowDialog.isEdit = true
      windowDialog.visible = true

      windowForm.id = row.id
      windowForm.name = row.name
      windowForm.description = row.description
      windowForm.status = row.status
    }

    // 处理删除窗口
    const handleDeleteWindow = (row) => {
      ElMessageBox.confirm(`确定要删除窗口"${row.name}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete("windows/" + row.id).then(res => {
          console.log(res)
          if (res.data.code === 200) {
            ElMessage.success('删除窗口成功')
            getList();
          } else {
            ElMessage.error(res.data.message);
          }
        });
      }).catch(() => {})
    }

    // 处理切换状态
    const handleToggleStatus = (row) => {
      const newStatus = row.status === 1 ? 0 : 1
      const statusText = newStatus === 1 ? '启用' : '禁用'

      ElMessageBox.confirm(`确定要${statusText}窗口"${row.name}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在模拟数据中更新状态
        const index = windowList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          windowList.value[index].status = newStatus
          ElMessage.success(`${statusText}窗口成功`)
        }
      }).catch(() => {})
    }

    // 处理配置业务类型
    const handleConfigBusinessType = (row) => {
      businessTypeDialog.windowId = row.id
      businessTypeDialog.windowName = row.name

      // 设置已选择的业务类型
      const selectedTypes = row.businessTypes.map(item => item.id)
      businessTypeDialog.selectedTypes = selectedTypes

      businessTypeDialog.visible = true
    }

    // 处理业务类型选择变化
    const handleBusinessTypeChange = () => {
      // 这里可以添加一些处理业务类型变化的逻辑
    }

    // 保存业务类型配置
    const saveBusinessTypes = () => {
      if (!businessTypeDialog.windowId) return

      // 更新窗口的业务类型
      const index = windowList.value.findIndex(item => item.id === businessTypeDialog.windowId)
      if (index !== -1) {
        // 根据选中的ID找到完整的业务类型对象
        const selectedBusinessTypes = mockBusinessTypes.filter(item =>
          businessTypeDialog.selectedTypes.includes(item.id)
        )

        windowList.value[index].businessTypes = selectedBusinessTypes
        ElMessage.success('配置业务类型成功')
        businessTypeDialog.visible = false
      }
    }

    // 提交窗口表单
    const submitWindowForm = () => {
      windowFormRef.value.validate((valid) => {
        if (valid) {
          const isEdit = windowDialog.isEdit
          windowForm.windowNumber = windowForm.id
          if (isEdit) {
            // 编辑现有窗口
            axios.put("/windows/" + windowForm.id, windowForm).then(() => {
              ElMessage.success('更新窗口成功')
              getList()
            });

          } else {
            axios.post("/windows/createWindow", windowForm).then(res => {
              getList()
              ElMessage.success('创建窗口成功')
            });
          }

          windowDialog.visible = false
        }
      })
    }

    onMounted(() => {
      // 初始化时不需要额外操作，模拟数据已加载
    })

    return {
      displayWindowList,
      tableLoading,
      pagination,
      filterForm,
      windowDialog,
      windowFormRef,
      windowForm,
      windowRules,
      businessTypeDialog,
      businessTypeOptions,
      handleSearch,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      handleRefresh,
      handleCreateWindow,
      handleEditWindow,
      handleDeleteWindow,
      handleToggleStatus,
      handleConfigBusinessType,
      handleBusinessTypeChange,
      saveBusinessTypes,
      submitWindowForm
    }
  }
}
</script>

<style scoped>
.window-management-container {
  padding: 15px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: 500;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.window-table {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.business-type-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.business-type-title {
  margin-bottom: 15px;
  font-size: 16px;
  color: #606266;
}
</style>
